document.addEventListener('DOMContentLoaded', function() {
    const videoContainer = document.getElementById('videoContainer');
    const noStreams = document.getElementById('noStreams');
    const addStreamBtn = document.getElementById('addStream');
    const streamNameInput = document.getElementById('streamName');
    const streamUrlInput = document.getElementById('streamUrl');

    let streamCount = 0;
    const streams = new Map(); // 存储所有流的信息

    // 添加视频流
    addStreamBtn.addEventListener('click', function() {
        const name = streamNameInput.value.trim() || `流 ${streamCount + 1}`;
        const url = streamUrlInput.value.trim();

        if (!url) {
            alert('请输入RTSP流地址');
            return;
        }

        if (!url.startsWith('rtsp://')) {
            alert('RTSP流地址应以 rtsp:// 开头');
            return;
        }

        // 生成唯一的流ID
        const streamId = 'stream_' + Date.now();

        // 显示加载状态
        addStreamBtn.disabled = true;
        addStreamBtn.textContent = '添加中...';

        // 首先通过API添加流到后端
        fetch('/api/streams/add', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                streamId: streamId,
                rtspUrl: url
            })
        })
            .then(response => {
                if (!response.ok) {
                    return response.text().then(text => {
                        throw new Error(text || `HTTP错误: ${response.status}`);
                    });
                }
                return response.text();
            })
            .then(data => {
                if (data.includes("ERROR") || data.includes("错误")) {
                    throw new Error(data);
                }

                // 清除输入框
                streamNameInput.value = '';
                streamUrlInput.value = '';

                // 隐藏"无视频流"提示
                noStreams.style.display = 'none';

                // 创建视频流播放器
                createVideoPlayer(name, url, streamId);
                streamCount++;
            })
            .catch(error => {
                console.error('添加流错误:', error);
                alert('添加流失败: ' + error.message);
            })
            .finally(() => {
                // 恢复按钮状态
                addStreamBtn.disabled = false;
                addStreamBtn.textContent = '添加流';
            });
    });

    // 创建视频播放器
    function createVideoPlayer(name, url, streamId) {
        const id = 'stream-' + Date.now();

        // 创建UI元素
        const wrapper = document.createElement('div');
        wrapper.className = 'video-wrapper';
        wrapper.id = id;

        wrapper.innerHTML = `
            <div class="video-header">
                <span class="video-title">${name}</span>
                <div class="video-controls">
                    <button class="control-btn pause" onclick="pauseStream('${id}', '${streamId}')">暂停</button>
                    <button class="control-btn resume" onclick="resumeStream('${id}', '${streamId}')" disabled>恢复</button>
<!--                    <button class="control-btn stop" onclick="stopStream('${id}', '${streamId}')">停止</button>-->
                    <button class="control-btn remove" onclick="removeStream('${id}', '${streamId}')">删除</button>
                    <button class="control-btn debug" onclick="debugStream('${id}', '${streamId}')">调试</button>
                </div>
            </div>
            <div class="video-content">
                <canvas id="canvas-${id}"></canvas>
            </div>
            <div class="status">
                <span class="stream-url" title="${url}">${url}</span>
                <span class="connection-status">
                    <span class="status-dot connecting"></span>
                    <span>连接中</span>
                </span>
            </div>
        `;

        videoContainer.appendChild(wrapper);

        // 初始化WebSocket连接和Canvas
        const canvas = document.getElementById(`canvas-${id}`);
        const ctx = canvas.getContext('2d');

        // 设置Canvas尺寸
        canvas.width = 640;
        canvas.height = 360;

        // 创建WebSocket连接
        let socket;
        let reconnectAttempts = 0;
        const MAX_RECONNECT_ATTEMPTS = 5;
        let reconnectTimeout = null;

        // 连接WebSocket
        function connectWebSocket() {
            // 清除之前的重连定时器
            if (reconnectTimeout) {
                clearTimeout(reconnectTimeout);
                reconnectTimeout = null;
            }

            // 如果已经达到最大重连次数，不再尝试
            if (reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {
                updateConnectionStatus(id, 'disconnected', '连接失败');
                return;
            }

            socket = new WebSocket('ws://' + window.location.host + '/video-stream');

            socket.onopen = function() {
                reconnectAttempts = 0;
                updateConnectionStatus(id, 'connected', '已连接');
                console.log(`WebSocket连接已建立: ${id}`);

                // 发送流订阅消息
                socket.send("streamId:" + streamId);
            };

            socket.onmessage = function(event) {
                if (typeof event.data === 'string') {
                    console.log('收到文本消息:', event.data);

                    if (event.data.startsWith("ERROR:")) {
                        updateConnectionStatus(id, 'disconnected', '错误');
                        alert("错误: " + event.data.substring(6));
                    } else if (event.data.startsWith("INFO:")) {
                        console.log("信息: " + event.data.substring(5));
                    }
                } else {
                    // 处理二进制帧数据
                    const blob = event.data;
                    const url = URL.createObjectURL(blob);
                    const img = new Image();

                    img.onload = function() {
                        // 使用requestAnimationFrame确保平滑渲染
                        requestAnimationFrame(() => {
                            ctx.clearRect(0, 0, canvas.width, canvas.height);
                            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

                            // 显示性能信息
                            const now = Date.now();
                            ctx.fillStyle = 'white';
                            ctx.font = '14px Arial';
                            ctx.fillText(`帧大小: ${blob.size} bytes`, 10, 20);
                            ctx.fillText(`分辨率: ${img.width}x${img.height}`, 10, 40);

                            URL.revokeObjectURL(url);
                            updateConnectionStatus(id, 'connected', '已连接');
                        });
                    };

                    img.onerror = function() {
                        console.error('图片加载失败');
                        URL.revokeObjectURL(url);
                        updateConnectionStatus(id, 'disconnected', '加载失败');
                    };

                    img.src = url;
                }
            };

            socket.onerror = function(error) {
                console.error(`WebSocket错误: ${id}`, error);
                updateConnectionStatus(id, 'disconnected', '连接错误');
            };

            socket.onclose = function(event) {
                console.log(`WebSocket连接关闭: ${id}`, event.code, event.reason);
                updateConnectionStatus(id, 'disconnected', '已断开');

                // 自动重连逻辑
                if (event.code !== 1000 && event.code !== 1001) {
                    reconnectAttempts++;
                    // const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 30000);
                    const delay = Math.min(3000, reconnectAttempts * 1000); // 指数退避，最多3秒
                    console.log(`将在 ${delay}ms 后尝试重连 (${reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})`);

                    reconnectTimeout = setTimeout(() => {
                        if (streams.has(id)) {
                            console.log(`尝试重连: ${id}`);
                            connectWebSocket();
                        }
                    }, delay);
                }else {
                    updateConnectionStatus(id, 'disconnected', '连接已关闭');
                }
            };
        }

        // 初始连接
        connectWebSocket();

        // 保存流信息
        streams.set(id, {
            name: name,
            url: url,
            streamId: streamId,
            // socket: socket,
            getSocket: () => socket, // 使用getter而不是直接存储socket

            canvas: canvas,
            ctx: ctx,

            reconnect: connectWebSocket,
            disconnect: () => {
                if (socket) {
                    socket.close(1000, '用户断开');
                }
                if (reconnectTimeout) {
                    clearTimeout(reconnectTimeout);
                    reconnectTimeout = null;
                }
            }
        });
    }

    // 更新连接状态
    function updateConnectionStatus(elementId, status, message) {
        const wrapper = document.getElementById(elementId);
        if (!wrapper) return;

        const statusDot = wrapper.querySelector('.status-dot');
        const statusText = wrapper.querySelector('.connection-status span:last-child');
        const controlButtons = wrapper.querySelectorAll('.control-btn');
        const reconnectBtn = wrapper.querySelector('.reconnect');

        statusDot.className = 'status-dot';
        statusText.textContent = message;

        switch (status) {
            case 'connected':
                statusDot.classList.add('connected');
                statusText.textContent = message || '已连接';
                // 启用控制按钮
                controlButtons.forEach(btn => {
                    if (!btn.classList.contains('remove')) {
                        btn.disabled = false;
                    }
                });
                if (reconnectBtn) {
                    reconnectBtn.style.display = 'none';
                }
                break;
            case 'disconnected':
                statusDot.classList.add('disconnected');
                statusText.textContent = message || '已断开';
                // 禁用控制按钮（除了删除按钮）
                controlButtons.forEach(btn => {
                    if (!btn.classList.contains('remove')) {
                        btn.disabled = true;
                    }
                });
                if (reconnectBtn) {
                    reconnectBtn.style.display = 'inline-block';
                    reconnectBtn.disabled = false;
                }
                break;
            case 'connecting':
                statusDot.classList.add('connecting');
                statusText.textContent = message || '连接中';
                // 禁用所有控制按钮
                controlButtons.forEach(btn => {
                    btn.disabled = true;
                });

                if (reconnectBtn) {
                    reconnectBtn.style.display = 'none';
                }
                break;
            case 'paused':
                statusDot.classList.add('paused');
                statusText.textContent = message || '已暂停';
                // 启用恢复按钮，禁用暂停按钮
                const pauseBtn = wrapper.querySelector('.pause');
                const resumeBtn = wrapper.querySelector('.resume');
                if (pauseBtn && resumeBtn) {
                    pauseBtn.disabled = true;
                    resumeBtn.disabled = false;
                }
                if (reconnectBtn) {
                    reconnectBtn.style.display = 'none';
                }
                break;
        }
    }

    // 全局函数，用于按钮点击
    // 暂停视频流
    window.pauseStream = function(elementId, streamId) {
        const stream = streams.get(elementId);
        if (!stream || stream.status !== 'playing') return;

        // 显示加载状态
        const wrapper = document.getElementById(elementId);
        if (wrapper) {
            const pauseBtn = wrapper.querySelector('.pause');
            pauseBtn.disabled = true;
            pauseBtn.textContent = '暂停中...';
        }

        fetch(`/api/streams/pause/${streamId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        })
            .then(response => {
                if (!response.ok) {
                    return response.text().then(text => {
                        throw new Error(text || `HTTP错误: ${response.status}`);
                    });
                }
                return response.text();
            })
            .then(data => {
                console.log('暂停响应:', data);

                // 更新UI状态
                updateConnectionStatus(elementId, 'paused', '已暂停');

                // 更新流状态
                stream.status = 'paused';
            })
            .catch(error => {
                console.error('暂停流错误:', error);

                // 恢复按钮状态
                const wrapper = document.getElementById(elementId);
                if (wrapper) {
                    const pauseBtn = wrapper.querySelector('.pause');
                    pauseBtn.disabled = false;
                    pauseBtn.textContent = '暂停';
                }

                // 显示具体的错误信息
                alert('暂停流失败: ' + error.message);
            });
    };

// 恢复视频流
    window.resumeStream = function(elementId, streamId) {
        const stream = streams.get(elementId);
        if (!stream || stream.status !== 'paused') return;

        fetch(`/api/streams/resume/${streamId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        })
            .then(response => {
                if (!response.ok) {
                    return response.text().then(text => {
                        throw new Error(text || `HTTP错误: ${response.status}`);
                    });
                }
                return response.text();
            })
            .then(data => {
                console.log('恢复响应:', data);

                // 更新UI状态
                updateConnectionStatus(elementId, 'connected', '已恢复');

                // 更新流状态
                stream.status = 'playing';
            })
            .catch(error => {
                console.error('恢复流错误:', error);
                alert('恢复流失败: ' + error.message);
            });
    };

// 停止视频流
    window.stopStream = function(elementId, streamId) {
        const stream = streams.get(elementId);
        if (!stream) return;

        fetch(`/api/streams/stop/${streamId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            }
        })
            .then(response => {
                if (!response.ok) {
                    return response.text().then(text => {
                        throw new Error(text || `HTTP错误: ${response.status}`);
                    });
                }
                return response.text();
            })
            .then(data => {
                console.log('停止响应:', data);

                // 关闭WebSocket连接
                if (stream.disconnect) {
                    stream.disconnect();
                }

                // 更新UI状态
                updateConnectionStatus(elementId, 'disconnected', '已停止');

                // 更新流状态
                stream.status = 'stopped';
            })
            .catch(error => {
                console.error('停止流错误:', error);
                alert('停止流失败: ' + error.message);
            });
    };

// 移除视频流
    window.removeStream = function(elementId, streamId) {
        const stream = streams.get(elementId);
        if (stream) {
            // 关闭WebSocket连接
            if (stream.disconnect) {
                stream.disconnect();
            }

            // 从Map中移除
            streams.delete(elementId);

            // 从后端移除流
            fetch(`/api/streams/remove/${streamId}`, {
                method: 'POST'
            })
                .then(response => {
                    if (!response.ok) {
                        return response.text().then(text => {
                            throw new Error(text || `HTTP错误: ${response.status}`);
                        });
                    }
                    return response.text();
                })
                .then(data => {
                    console.log('移除流响应:', data);
                })
                .catch(error => {
                    console.error('移除流错误:', error);
                    alert('移除流失败: ' + error.message);
                });
        }

        // 从DOM中移除
        const element = document.getElementById(elementId);
        if (element) {
            element.remove();
        }

        // 如果没有视频流了，显示提示
        if (streams.size === 0) {
            noStreams.style.display = 'block';
            streamCount = 0;
        }
    };
    // 添加重连函数
    window.reconnectStream = function(elementId) {
        const stream = streams.get(elementId);
        if (stream && stream.reconnect) {
            updateConnectionStatus(elementId, 'connecting', '正在重连...');
            stream.reconnect();
        }
    };

    window.debugStream = function(elementId, streamId) {
        // 调试功能：获取统计信息
        fetch(`/api/streams/stats/${streamId}`)
            .then(response => response.json())
            .then(data => {
                console.log('流统计信息:', data);
                alert('流统计信息: ' + JSON.stringify(data, null, 2));
            })
            .catch(error => {
                console.error('获取统计信息错误:', error);
            });

        // 发送测试帧
        fetch(`/api/streams/test/${streamId}`)
            .then(response => response.text())
            .then(data => {
                console.log('测试帧响应:', data);
            })
            .catch(error => {
                console.error('测试帧错误:', error);
            });
    };

});